package com.allinpay.merchantweb.service.impl;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeSet;
import java.util.concurrent.TimeUnit;

import javax.servlet.http.HttpServletRequest;

import org.apache.http.Consts;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.data.redis.serializer.RedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;

import com.alibaba.fastjson.JSON;
import com.allinpay.merchantweb.common.exception.ViewException;
import com.allinpay.merchantweb.common.utils.StringUtil;
import com.allinpay.merchantweb.constants.CommonConstants;
import com.allinpay.merchantweb.constants.ReturnCodeConstants;
import com.allinpay.merchantweb.redismodel.RedisData;
import com.allinpay.merchantweb.response.UserResponse;
import com.allinpay.merchantweb.service.EncodeAndDecodeService;
import com.allinpay.merchantweb.service.RedisService;
import com.google.common.collect.Lists;
import com.google.gson.Gson;




@Service
public class RedisServiceImpl implements RedisService {

    private static final Logger logger = LoggerFactory.getLogger(RedisServiceImpl.class);

    @SuppressWarnings("rawtypes")
    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private EncodeAndDecodeService encodeAndDecodeService;
	/**
     * 功能：注入
     * 
     */
   @Autowired(required = false)
    public void setRedisTemplate(RedisTemplate redisTemplate) {
        RedisSerializer stringSerializer = new StringRedisSerializer();
        redisTemplate.setKeySerializer(stringSerializer);
        redisTemplate.setValueSerializer(stringSerializer);
        this.redisTemplate = redisTemplate;
    }
   
   /**
    * 功能：缓存String数据
    * 
    */
  
    public void setRedisStringData(String key, String redisData, int inValidTime, TimeUnit unit) {
        ValueOperations<String, String> operations1 = redisTemplate.opsForValue();
        operations1.set(key, redisData, inValidTime, unit);
    }

    /**
     * 功能：缓存String数据（永久有效）
     * 
     */

    public void setRedisStringData(String key, String redisData) {
        ValueOperations<String, String> operations1 = redisTemplate.opsForValue();
        operations1.set(key, redisData);
    }


    /**
     * 功能：缓存对象数据
     * 
     */

    public void setRedisObjectData(String key, RedisData redisData, int inValidTime, TimeUnit unit) {
    	String json=JSON.toJSONString(redisData);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(key, json, inValidTime, unit);
    }

    /**
     * 功能：缓存对象数据（永久有效）
     * 
     */

    public void setRedisObjectData(String key, RedisData redisData) {
    	String json=JSON.toJSONString(redisData);
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        operations.set(key, json);
    }

    /**
     * 功能：获取缓存对象数据
     * 
     */
    public RedisData getRedisObjectData(String key,RedisData redisDatatemp) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
        	String json=operations.get(key);
            RedisData redisData = JSON.parseObject(json, redisDatatemp.getClass());
            return redisData;
        }
        return null;
    }

    /**
     * 功能：获取缓存String数据
     * 
     */
    public String getRedisStringData(String key) {
        ValueOperations<String, String> operations = redisTemplate.opsForValue();
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
            String redisData = operations.get(key);
            return redisData;
        }
        return null;
    }

    /**
     * 功能：清除缓存String数据
     * 
     */
    public void DeLRedisStringData(String key) {
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
        	redisTemplate.delete(key);
        }
    }
    
    /**
     * 功能：清除缓存对象数据
     * 
     */
    public void DeLRedisObjectData(String key) {
        // 缓存存在
        boolean hasKey = redisTemplate.hasKey(key);
        if (hasKey) {
        	redisTemplate.delete(key);
        }
    }
    
    /**
     * HashGet
     * 
     * @param key
     *            键 不能为null
     * @param item
     *            项 不能为null
     * @return 值
     */
    public Object hget(String key, String item) {
        return redisTemplate.opsForHash().get(key, item);
    }
    
    public  String isInSession(Model model, HttpServletRequest request) {
	    String sessionId=request.getRequestedSessionId();
	    String backUrl = request.getParameter("backUrl");
	    logger.info("current sessionId:"+sessionId);
       
        return null;
    }
    
    public Model overtimes(String backUrl,Model model) {
        //定义返回Map
        Map backMap = new HashMap<String, Object>();
        try {        
        	//获取data
        	UserResponse data=new UserResponse();
        	data.setAppId("");
        	data.setName("");
        	data.setIsUpdatedPwd("");
        	data.setOpenId("");
        	Gson gson = new Gson();
        	String jsonStr=gson.toJson(data);
        	String dataresult=jsonStr;
            List<NameValuePair> params2 = Lists.newArrayList();
            params2.add(new BasicNameValuePair("data", dataresult));
            dataresult = EntityUtils.toString(new UrlEncodedFormEntity(params2, Consts.UTF_8));
            logger.info("data:" + dataresult);
        	
        	//获取签名原串
        	Map newMap = new HashMap<String, Object>();
        	newMap.put("data",jsonStr);
        	newMap.put("signType",CommonConstants.SIGNTYPE); 
            String signMsg=this.orderMap2Str(newMap);
        	logger.info("signMsg签名原串:" + signMsg);
            
            //获取签名串
            String resultSign = encodeAndDecodeService.sign(signMsg);
            List<NameValuePair> params = Lists.newArrayList();
            params.add(new BasicNameValuePair("sign", resultSign));
            resultSign = EntityUtils.toString(new UrlEncodedFormEntity(params, Consts.UTF_8));
            logger.info("resultSign签名串:" + resultSign);
            
            //返回 code ,msg ,data ,sign ,signType
            model.addAttribute("data", dataresult);  
            model.addAttribute("sign", resultSign);  
            model.addAttribute("signType", CommonConstants.SIGNTYPE);  
            model.addAttribute("backUrl", backUrl);  
        } catch (Exception e) {
            logger.error("h5regist error:" + e);
            model.addAttribute("code", "");  
            model.addAttribute("msg", "未知页面异常"); 
        }
        return model;
    }
    
	public static String orderMap2Str(Map<String, Object> map) {
        Set<String> keySet = new TreeSet(map.keySet());
        StringBuilder sb = new StringBuilder();
        for (String key : keySet) {
            if (Map.class.isInstance(map.get(key))
                    || List.class.isInstance(map.get(key))
                    || StringUtil.isEmpty(String.valueOf(map.get(key)))
                    || map.get(key)==null
                    || "loginName".equals(key)) {
                continue;
            }
            sb.append(key).append("=").append(map.get(key)).append("&");
        }
        sb.setLength(sb.length() - 1);
        return sb.toString();
    }
}
